package com.itcat.interceptor;

import com.itcat.mysql.pojo.UmsAdmin;
import com.itcat.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * [Token拦截器]
 *
 * @author : [Cr Mr]
 * @version : [v1.0]
 * @date : [2022/3/16 20:25]
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头
        String token = request.getHeader("Authorization");

        log.info("token:" + token);

        //2、使用工具类，判断token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);

        //3、如果token失效，返回状态码401，拦截
        if (!verifyToken) {
            response.setStatus(401);
            return false;
        }
        //4、如果token正常可用，放行

        //解析token，获取id和手机号码，构造User对象，存入Threadlocal
        Claims claims = JwtUtils.getClaims(token);
        Long id = claims.get("id", Long.class);
        String username = claims.get("username", String.class);
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setId(id);
        umsAdmin.setUsername(username);
        UserHolder.set(umsAdmin);
        return true;
    }
}
